package com.lly.thread;


import java.io.IOException;
import java.util.concurrent.*;

public class FFmpegThreadPoolExecutor {
    /**
     * 执行线程池
     */
    private static ExecutorService executorService = null;
    /**
     * 任务列表
     */
    private static ConcurrentHashMap<String ,FFmpegRunner> ffmpegTasksMap = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String ,FFmpegRunner> getTasks(){
        return ffmpegTasksMap;
    }


    static {
        if (executorService == null){
            initExecutor();
        }
    }

    public static void addTask(String threadName,FFmpegRunner r){

        executorService.execute(r);
        ffmpegTasksMap.put(threadName, r);
    }

    public static void earlyTermination(String taskName){
        if (ffmpegTasksMap.containsKey(taskName)){
            FFmpegRunner runner = ffmpegTasksMap.get(taskName);
            try {
                runner.close();
                if (runner.isClose()){
                    ffmpegTasksMap.remove(taskName);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭线程池
     */
    public static void shutdownExecutor(){
        if (executorService != null && !executorService.isShutdown()){
            executorService.shutdown();
            ffmpegTasksMap.clear();
        }
    }


    public static void initExecutor(){
        if (executorService == null || executorService.isShutdown()){
            executorService = Executors.newCachedThreadPool();
            ffmpegTasksMap.clear();
        }
    }


}
